export default {
  name: 'login',
  data () {
    return {
      info: {},
      // 表单规则验证
      loginRules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'change' },
          { min: 3, message: '最少输入三位字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'change' },
          { min: 3, message: '最少输入三位字符', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 表单重置事件处理函数
    resetHandler () {
      this.$refs.login.resetFields()
    },
    // 表单提交事件处理函数
    submitHandler () {
      this.$refs.login.validate(
        async valid => {
          if (!valid) {
            this.$message({
              type: 'warning',
              message: '请按照规则填写表单',
              duration: 1500
            })
            return
          }
          const { data, meta } = await this.$post('login', this.info)
          if (meta.status === 400) {
            this.$message({
              type: 'error',
              message: '用户名密码错误，请重新登录',
              duration: 3000
            })
            return
          }
          // 把token 存储到sessionStorage里
          window.sessionStorage.setItem('token', data.token)
          this.$message({
            type: 'success',
            message: '登录成功，即将跳转',
            duration: 1500
          })
          setTimeout(() => {
            this.$router.push('/home')
          }, 1500)
        }
      )
    }
  }
}
